import {defineStore} from 'pinia'
import request from '@/utils/request'
import {ApiRes} from '@/types/data'
import {Profile} from '@/types/user'
import {setProfile,getProfile,removeProfile} from '@/utils/storage'


const useUserStore = defineStore('user',{
    state(){
        return {
           profile: getProfile() as Profile
        }
    },
    actions:{
        // 账号登录
        async login(account:string,password:string){
            const res = await request.post<ApiRes<Profile>>('/login',{account,password})
            this.profile = res.data.result
            setProfile(res.data.result)
        },
        // 手机验证码登录
        async loginMobile(mobile:string,code:string){
            const res = await request.post<ApiRes<Profile>>('/login/code',{mobile,code})
            this.profile = res.data.result
            setProfile(res.data.result)
        },

        // qq登录
        async qqLogin(openId:string){
            const res = await request.post('/login/social',{
                unionId:openId,
                source:6
            })
            this.profile = res.data.result
            setProfile(res.data.result)
        },

        // 获取手机验证码
        async sendMobileMsg(mobile:string){
            await request.get('/login/code',{params:{mobile}})
            // 思考:需要返回值吗? 不需要
        },

        // 获取QQ与手机绑定的验证码
        async sendQQBindMsg(mobile: string) {
            await request.get('/login/social/code', {
              params: {
                mobile
              }
            })
        },
        
        // QQ与账号绑定
        async qqBindLogin(openId: string, mobile: string, code: string) {
            const res = await request.post<ApiRes<Profile>>('/login/social/bind', {
              mobile,
              code,
              unionId: openId
            })
            // 1. 保存用户信息到 state 中
            this.profile = res.data.result
            setProfile(res.data.result)
        },

        // 获取短信验证码
        // 绑定qq的短信验证码
        async sendQQPathMsg(mobile: string) {
            await request.get('/register/code', {
            params: {
                mobile
            }
            })
        },
        
        async qqPatchLogin(data: any) {
            const res = await request.post<ApiRes<Profile>>(
            `/login/social/${data.openId}/complement`,
            data
            )
            // 1. 保存用户信息到 state 中
            this.profile = res.data.result
            setProfile(res.data.result)
        },

        // 退出
        logout(){
            this.profile = {} as Profile
            removeProfile()
        }


    },
    getters:{}
})

export default useUserStore